nginx代理

1
[root@lnmp ~]# vim /usr/local/nginx/conf/vhosts/proxy.conf

        加入内容:

1
2
3
4
5
6
7
8
9
10
11
12
server {
listen 80;
server_name www.baidu.com;
location / {
proxy_pass http://180.97.33.107/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# access_log /home/logs/baidu.access combined;
}

        说明:proxy_pass 后面跟要代理机器的 ip 。如果后端的机器有多台,还可以用 upstream 来实现负载均衡,配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
upsteam baidu {
server 180.97.33.108:80;
server 180.97.33.107:80;
}
server {
listen 80;
server_name www.baidu.com;
location / {
proxy_pass http://baidu/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# access_log /home/logs/baidu.access combined;
}

        说明: upstream 后面的名字是自定义的,这个名字会放到 proxy_pass 后面。

        还可以代理一个服务器上所有域名,首先在 vhosts 目录下需要建立两个文件,一个是 servername 列表文件,一个是虚拟主机配置文件。两个文件内容分别为

1.servername

1
[root@lnmp ~]# vim /usr/local/nginx/conf/vhosts/servername

        加入内容:

1
server_name www.123.com www.234.com www.345.com;

        就这么简单一行,这个server_name 还可以继续添加

2.虚拟主机配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@lnmp ~]# vim /usr/local/nginx/conf/vhosts/proxy_all.conf
server {
listen 80;
include vhosts/servername;
location / {
proxy_pass http://1.2.1.2/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
access_log /dev/null;
}

        include vhosts/servername; 这个文件就是上边那个 servername 列表文件;

        proxy_pass http://1.2.1.2/; 就是需要做代理的服务器 ip 地址